package com.itheima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.itheima.admin.feign.AdChannelFeign;
import com.itheima.admin.pojo.AdChannel;
import com.itheima.common.constants.SystemConstants;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.vo.ResultVo;
import com.itheima.wemedia.service.ApiService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @version 1.0
 * @description 说明
 * @package com.itheima.wemedia.service.impl
 */
@Service
public class ApiServiceImpl implements ApiService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    
    @Autowired
    private AdChannelFeign adChannelFeign;

    /**
     * 调用后台微服务，获取频道列表。
     * 优先使用redis缓存
     *
     * @return
     */
    @Override
    public List<AdChannel> getChannelList() {
        //从redis获取
        String key = SystemConstants.REDISKEY_CHANNELLIST;
        String channelListInRedis = stringRedisTemplate.opsForValue().get(key);
        List<AdChannel> channelList = null;
        //有数据
        if (!StringUtils.isEmpty(channelListInRedis)){
            channelList = JSON.parseArray(channelListInRedis, AdChannel.class);
        }else {
            //没有数据--远程调用
            ResultVo<List<AdChannel>> listResultVo = adChannelFeign.listAll();
            if (!listResultVo.isSuccess()){
                throw new LeadNewsException("查询频道列表失败！");
            }
            channelList = listResultVo.getData();

            //防止缓存穿透，没有数据也存入redis,设置短暂有效期
            if (CollectionUtils.isEmpty(channelList)){
                stringRedisTemplate.opsForValue().set(key,null);
            }else {
                stringRedisTemplate.opsForValue().set(key,JSON.toJSONString(channelList));
            }
        }
        return channelList;
        /*//1.从redis获取

        String channelListJsonList = stringRedisTemplate.opsForValue().get(SystemConstants.REDISKEY_CHANNELLIST);
        List<AdChannel> chanelList = null;
        //判断redis是否有值
        if (StringUtils.isNotEmpty(channelListJsonList)){
        //有值转换List<AdChannel>
            chanelList = JSON.parseArray(channelListJsonList, AdChannel.class);
        }
        //无值调用admin查询频道列表
        if (StringUtils.isEmpty(channelListJsonList)){
            ResultVo<List<AdChannel>> listResultVo = adChannelFeign.listAll();
            if (!listResultVo.isSuccess()){
                throw new LeadNewsException("调用后台查询频道列表失败！");
            }
            chanelList = listResultVo.getData();
            //存入redis
          stringRedisTemplate.opsForValue().set(SystemConstants.REDISKEY_CHANNELLIST, JSON.toJSONString(chanelList));
        }
        //返回结果
        return chanelList;*/
    }
}
